<template>
<div>
    <NavigationBar />
    <el-container>
        <el-header class="header">
          <h1>我的消息</h1>
        </el-header>
        <el-main>
            <el-table :data="messages" style="width: 100%">
                <el-table-column prop="message_ID" label="消息 ID" width="150" />
                <el-table-column prop="message_type" label="消息类型" width="150">
                    <template #default="scope">
                    <el-tag :type="getMessageTypeTagType(scope.row.message_type)">
                        {{ getMessageTypeText(scope.row.message_type) }}
                    </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="message_content" label="消息内容" />
                <el-table-column prop="time" label="时间" width="180" />
            </el-table>
        </el-main>
    </el-container>
</div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useStore } from 'vuex'; // 用于访问 Vuex store 中的数据
import axios from '@/axios'
import NavigationBar from '@/components/NavigationBar.vue';

const store = useStore(); // 使用 useStore 函数获取 Vuex Store 实例

const messages = ref([]); // 用于存放消息数据

const fetchMessages = async () => {
    try {
        const user_ID = store.state.user.id;
        const response = await axios.get(`/api/user/messages?user_ID=${user_ID}`);
        messages.value = response.data;
        // 按时间排序，时间晚的在前面
        fetchedMessages.sort((a, b) => new Date(b.time) - new Date(a.time));

        messages.value = fetchedMessages;
    } catch (error) {
        console.error('Error fetching messages:', error);
    }
};

/* 根据消息类型返回相应的文本描述 */
const getMessageTypeText = (type) => {
    switch (type) {
        case 0:
            return '预定确认';
        case 1:
            return '订单状态更新';
        default:
            return '未知类型';
    }
};

/* 根据消息类型返回相应的标签样式 */
const getMessageTypeTagType = (type) => {
    switch (type) {
        case 0:
            return 'success';
        case 1:
            return 'info';
        default:
            return '';
    }
};

/* 在组件挂载时调用 fetchMessages 函数来获取消息数据 */
onMounted(() => {
    fetchMessages();
});
</script>

<style scoped>
.header {
  background-color: #ffffff;
  padding: 20px;
  border-bottom: 1px solid #ddd;
}

.header h1 {
  margin: 0;
  font-size: 28px;
  color: #333;
}
.el-main {
  padding: 20px;
}

.el-table th,
.el-table td {
  text-align: center;
}

.el-table-column--align-center .cell {
  justify-content: center;
}
</style>
  